package com.atguigu.ssyx.acl.utils;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: PermissionHelper
 * Package: com.atguigu.ssyx.acl.utils
 * Description:
 *
 * @Author Root
 * @Create 2023/9/15 9:21
 * @Version 1.0
 */
public class PermissionHelper {
    public static List<Permission> buildPermission(List<Permission> allList) {
        //创建最终数据封装List集合
        List<Permission> trees=new ArrayList<>();
        //遍历所有菜单list集合，得到第一层数据，pid=0
        for (Permission permission : allList) {
            if(permission.getPid()==0){
                permission.setLevel(1);
                //调用方法，从第一层开始往下找
                trees.add(findChildren(permission,allList));
            }
        }

        return trees;

    }

    //递归往下找
    private static Permission findChildren(Permission permission, List<Permission> allList) {
        permission.setChildren(new ArrayList<Permission>());
        //遍历allList所有菜单数据
        //判断：当前节点id=pid是否一样，封装递归
        for (Permission it : allList) {
            if(permission.getId().longValue()==it.getPid().longValue()){
                int level=permission.getLevel()+1;
                it.setLevel(level);
                //封装下一层数据
                permission.getChildren().add(findChildren(it,allList));
            }
        }
        return permission;
    }
}
